const fs = require("fs");
const path = require('path');

/**
 * use全局参数
 * agreement 协议头
 * uploadPathdir 上传文件夹
 */
/*上传图片*/
const upload_file_image = (req, res) => {
	let obj_file = {
		code: -1,
		path: "",
		type: '',
		msg: "上传失败"
	};
	try {
		res.header("Access-Control-Allow-Origin", "*");
		let file = req.file || 'null';
		let filetype = (req.file && req.file.mimetype) || 'null';
		obj_file.type = filetype;
		if (file === 'null') {
			obj_file.msg = "请上传文件";
			res.end(JSON.stringify(obj_file));
			return;
		}
		const {
			originalname,
			filename,
			mimetype,
			size
		} = file;
		let newFilePath;
		if (isProd) {
			newFilePath = `${agreement}://${req.hostname}/imgs/${filename}`;
		} else {
			newFilePath = `${agreement}://${req.hostname}:${port}/imgs/${filename}`;
		}
		let dirPath = `/imgs/${filename}`;
		obj_file = {
			...obj_file,
			code: 200,
			msg: "上传成功",
			...{
				originalname,
				filename,
				path: newFilePath,
				dirPath,
				mimetype,
				size,
			}
		}
		res.end(JSON.stringify(obj_file));
	} catch (e) {
		//TODO handle the exception
		obj_file.msg = e.message
		res.end(JSON.stringify(obj_file));

	}
}
module.exports = upload_file_image;
